package com.dy.yunying.biz.controller.manage;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.yunying.api.entity.WanGameDO;
import com.dy.yunying.api.req.WanGameImgsReq;
import com.dy.yunying.api.req.WanGameReq;
import com.dy.yunying.api.resp.WanGameRes;
import com.dy.yunying.api.vo.WanGameReqVo;
import com.dy.yunying.biz.service.manage.AdRoleGameService;
import com.dy.yunying.biz.service.manage.GameService;
import com.dy.yunying.biz.service.manage.WanCmsConfigService;
import com.dy.yunying.biz.service.manage.WanGameImgsService;
import com.dy.yunying.biz.utils.CheckResult;
import com.dy.yunying.biz.utils.PingYinUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 子游戏管理
 */
@RestController
@RequestMapping("/game")
public class GameController {

	private static Logger logger = LoggerFactory.getLogger(GameController.class);

	@Autowired
	private GameService gameService;
	@Autowired
	private WanGameImgsService wanGameImgsService;
	@Autowired
	private WanCmsConfigService wanCmsConfigService;
	@Autowired
	private AdRoleGameService adRoleGameService;

	/**
	 * 获取可缓存的子游戏列表
	 *
	 * @return
	 */
	@PostMapping(value = "/getCacheableGameList")
	public R<List<WanGameDO>> getCacheableGameList(@RequestBody WanGameReq req) {
		try {
//			LambdaQueryWrapper<WanGameDO> wrapper = Wrappers.<WanGameDO>query().lambda().select(WanGameDO::getId, WanGameDO::getGname).orderByDesc(WanGameDO::getId);
//			Optional.ofNullable(req).map(WanGameReq::getIds).filter(e -> !e.isEmpty()).ifPresent(e -> wrapper.in(WanGameDO::getId, e));
//			List<WanGameDO> gameList = gameService.getBaseMapper().selectList(wrapper);

			List<WanGameDO> gameList = gameService.getCacheableGameList(req);
			return R.ok(gameList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return R.failed("查询列表失败");
		}
	}

	/**
	 * 游戏列表
	 *
	 * @return
	 */
	@SysLog("子游戏管理")
	@RequestMapping(value = "/list.json")
	public R list(WanGameReq req) {
		if (null == req.getPgid()) {
			return R.failed("未获取到父游戏ID");
		}
		try {
			Page pge = new Page();
			pge.setSize(req.getSize());
			pge.setCurrent(req.getCurrent());
			//获取自身角色下的子游戏id列表
			req.setIds(adRoleGameService.getOwnerRoleGameIds());
			IPage<WanGameReqVo> list = gameService.selectGameList(req);
			return R.ok(list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return R.failed("查询列表失败");
		}
	}

//	/**
//	 * 游戏列表 for 下拉菜单
//	 *
//	 * @return
//	 */
//	@RequestMapping(value = "/game_list.json")
//	public R<List<Map<String, Object>>> gameListForDropdown(WanGameReq req) {
//		R<List<Map<String, Object>>> result = new R<>();
//		try {
//			req.setStatus(30);//状态  30：正常，40：停运
//			IPage<WanGameReqVo> games = gameService.selectGameList(null);
//
//			List<Map<String, Object>> data = new ArrayList<>();
//
//			for (WanGameReqVo item : games.getRecords()) {
//				Map<String, Object> map = new HashMap<>();
//
//				map.put("name", item.getGname());
//				map.put("value", item.getId());
//
//				data.add(map);
//			}
//
//			result.setData(data);
//			return result;
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//			return result;
//		}
//	}

	/**
	 * 新增游戏
	 *
	 * @return
	 */
	@SysLog("新增子游戏")
	@RequestMapping(value = "/add.json")
	public R<Map<String, Object>> add(HttpServletRequest request) {
		WanGameReqVo entity = new WanGameReqVo();
		CheckResult checkResult = check(request, entity, "add");
		if (!checkResult.isStatus()) {
			return R.failed(checkResult.getMessage());
		}
		try {
			BigInteger id = gameService.insertWanGame(entity);
			if (id != null) {
				// 游戏详细图片
				String detailsimgs = request.getParameter("detailsimg");
				if (StringUtils.isNotBlank(detailsimgs)) {
					String[] list = detailsimgs.split(",");
					List<WanGameImgsReq> imglist = new ArrayList<WanGameImgsReq>();
					for (int i = 0; i < list.length; i++) {
						WanGameImgsReq wgi = new WanGameImgsReq();
						wgi.setGid(id.intValue());
						wgi.setImgurl(list[i]);
						wgi.setIdx(i + 1);
						wgi.setImgtype("2");
						imglist.add(wgi);
					}
					if (CollectionUtils.isNotEmpty(imglist)) {
						wanGameImgsService.insertWanGameImgsList(imglist);
					}
				}
				return R.ok();
			} else {
				return R.failed("操作失败");
			}
		} catch (Exception e) {
			logger.error("game add fail, ", e);
			return R.failed("操作失败");
		}

	}

	/**
	 * 修改游戏
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@SysLog("修改子游戏")
	@RequestMapping(value = "/edit.json")
	public R<Map<String, Object>> doGameModify(HttpServletRequest request, HttpServletResponse response) {
		WanGameReqVo entity = new WanGameReqVo();
		CheckResult checkResult = check(request, entity, "update");
		if (!checkResult.isStatus()) {
			return R.failed(checkResult.getMessage());
		}
		try {
			String oldPkname = entity.getOldPkName();
			String pkName = entity.getPk_name();
			if (!oldPkname.equals(pkName)) {
				// 老的app名称和新app名称不一样是  确定编辑了app名称
				entity.setIs_update(1);
			}
			boolean flag = gameService.updateWanGameByPrimaryKey(entity);
			if (flag == true) {
				//刷新缓存
				//sysConfigBean.refreshSysConfig();

				//游戏详情图片
				String detailsimgs = request.getParameter("detailsimg");
				if (StringUtils.isNotBlank(detailsimgs)) {
					//删除
					WanGameImgsReq delwgi = new WanGameImgsReq();
					delwgi.setGid(entity.getId().intValue());
					wanGameImgsService.deleteWanGameImgs(delwgi);
					//插入新图
					String[] list = detailsimgs.split(",");
					List<WanGameImgsReq> imglist = new ArrayList<WanGameImgsReq>();
					for (int i = 0; i < list.length; i++) {
						WanGameImgsReq wgi = new WanGameImgsReq();
						wgi.setGid(entity.getId().intValue());
						wgi.setImgurl(list[i]);
						wgi.setIdx(i + 1);
						wgi.setImgtype("2");
						imglist.add(wgi);
					}
					if (CollectionUtils.isNotEmpty(imglist)) {
						wanGameImgsService.insertWanGameImgsList(imglist);
					}
				}

				wanCmsConfigService.insertWanCmsConfig("游戏中心-" + entity.getGname(), "1", "games", entity.getId().intValue());
				return R.ok();
			} else {
				return R.failed("操作失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed("操作失败");
		}
	}

	/**
	 * 删除，批量删除
	 *
	 * @param request
	 * @return
	 */
	@SysLog("删除子游戏")
	@RequestMapping(value = "/delete.json")
	public R<Map<String, Object>> batchDelete(HttpServletRequest request, HttpServletResponse response) {
		String ids = request.getParameter("ids");
		if (StringUtils.isBlank(ids)) {
			return R.failed("参数错误");
		}
		try {
			String[] idList = ids.split(",");
			Map<String, Object> result = gameService.batchDelete(idList);
			return R.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed("操作失败");
		}
	}

	public CheckResult check(HttpServletRequest request, WanGameReqVo entity, String type) {
		String pgid = request.getParameter("pgid");//父游戏ID
		String enname = request.getParameter("enname");//游戏名称
		String gname = request.getParameter("gname");//游戏名称
		String officialurl = request.getParameter("officialurl");// 官网地址
		String gtypes = request.getParameter("gtypes");// 游戏类型
		String gthemes = request.getParameter("gthemes");// 游戏题材
		String gstatus = request.getParameter("status");// 游戏状态
		String cstatus = request.getParameter("cstatus");// 游戏推荐状态
		String remark = request.getParameter("remark");// 游戏简介
		String icon = request.getParameter("icon");// 全部游戏(80*80)
		String picture = request.getParameter("picture");// 首页热门/游戏大厅(250*134)
		String rcmdimg = request.getParameter("rcmdimg");// 推荐展示图片(218*250)
		String terminaltype = request.getParameter("terminaltype");// 终端类型
		String qrcodeimg = request.getParameter("qrcodeimg");// 二维码
		String bannerimg = request.getParameter("bannerimg");// 详情横幅图
		String downloadurl = request.getParameter("downloadurl");// 下载地址
		String size = request.getParameter("size");// 包大小
		String seo_keywords = request.getParameter("seo_keywords");//seo信息
		String seo_description = request.getParameter("seo_description");
		String playurl = request.getParameter("playurl");//登陆链接
		String pk_name = request.getParameter("pk_name");//APP包名
		String bundleid = request.getParameter("bundleid");//IOS bundleid
		String exchange_url = request.getParameter("exchange_url");//充值回调地址
		String isrecharge = request.getParameter("isrecharge");//是否充值
		String display = request.getParameter("display");//是否展示到网站
		String description = request.getParameter("description");//游戏描述
		String detailsimgs = request.getParameter("detailsimg");//游戏详细图片
		String domain = request.getParameter("domain");//域名
		String ratio = request.getParameter("ratio");//游戏分成
		String app_name = request.getParameter("app_name");//app应用名称
		String app_icon = request.getParameter("app_icon");//app应用图标
		String oldPkName = request.getParameter("oldPkName");//app应用图标
		String gameLogo = request.getParameter("gameLogo");//游戏Logo

		String loginMap = request.getParameter("loginMap");//游戏登录图
		String logingMap = request.getParameter("logingMap");//游戏LOGING图

		entity.setOldPkName(oldPkName);
		CheckResult result = new CheckResult();
		StringBuilder msg = new StringBuilder("");
		boolean flag = true;
		if (StringUtils.equals("update", type)) {
			// 游戏id
			String id = request.getParameter("id");
			if (StringUtils.isNotBlank(id)) {
				entity.setId(new BigInteger(id));
			} else {
				msg.append("ID不能为空");
				flag = false;
			}
		}
		if (StringUtils.isNotBlank(pgid)) {
			entity.setPgid(new BigInteger(pgid));
		} else {
			msg.append("父游戏ID为空");
			flag = false;
		}
		if (StringUtils.isNotBlank(gname)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("gname", gname);
			map.put("isdelete", 0);
			WanGameReqVo game = gameService.selectWanGameByCond(map);
			if (game != null) {
				if (StringUtils.equals("update", type)) {
					String id = request.getParameter("id");
					if (StringUtils.isNotBlank(id)) {
						if (!String.valueOf(game.getId()).equals(id) ) {
							msg.append("已存在相同名称的游戏");
							flag = false;
						}
					}
				} else {
					msg.append("已存在相同名称的游戏");
					flag = false;
				}
			}
			entity.setGname(gname);
			entity.setFirstletter(PingYinUtils.getFirstletter(gname));
		} else {
			msg.append("游戏名称不能为空");
			flag = false;
		}
		if (StringUtils.isNotBlank(terminaltype)) {
			entity.setTerminaltype(Integer.parseInt(terminaltype));
		} else {
			msg.append("请选择游戏端口");
			flag = false;
		}
		//游戏别名
		if (StringUtils.isNotBlank(enname)) {
			if (StringUtils.equals("update", type)) {
				if (enname.matches("^[A-Za-z0-9]+$")) {
					entity.setEnname(enname);
				} else {
					msg.append("游戏别名由英文字母和数字组成");
					flag = false;
				}
			} else {
				if (enname.matches("^[A-Za-z0-9]+$")) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("enname", enname);
					map.put("isdelete", 0);
					WanGameReqVo game = gameService.selectWanGameByCond(map);
					if (null != game) {
						msg.append("已存在相同游戏别名");
						flag = false;
					} else {
						entity.setEnname(enname);
					}
				} else {
					msg.append("游戏别名由英文字母和数字组成");
					flag = false;
				}
			}
		} else {
			//当新增为空时，生成汉字首字母
			if (StringUtils.equals("add", type)) {
				entity.setEnname(PingYinUtils.getPinYinHeadCharToUppercase(gname.trim()));
			}else{
				entity.setEnname("");
			}
		}
		//回调地址
		if (StringUtils.isNotBlank(exchange_url)) {
			if (exchange_url.matches("[a-zA-z]+://[^\\s]*")) {
				entity.setExchange_url(exchange_url);
			} else {
				msg.append("请输入正确的充值回调地址");
				flag = false;
			}
		}
		//Android手游
		if ("2".equals(terminaltype)) {
			if (StringUtils.isNotBlank(pk_name)) {
				if (pk_name.matches("([a-zA-Z_][a-zA-Z0-9_]*[.])*([a-zA-Z_][a-zA-Z0-9_]*)$")) {
					entity.setPk_name(pk_name);
				} else {
					msg.append("APP包名格式验证失败，例：com.sjda.GameApi");
					flag = false;
				}
			} else {
				msg.append("请选择输入APP包名");
				flag = false;
			}
		}
		//IOS手游
		if ("3".equals(terminaltype)) {
			if (StringUtils.isNotBlank(bundleid)) {
				entity.setBundleid(bundleid);
			} else {
				msg.append("请输入bundleID");
				flag = false;
			}
		}
		//域名
		if (StringUtils.isNotBlank(domain)) {
			if (domain.matches("[a-zA-z]+://[^\\s]*")) {
				entity.setDomain(domain);
			} else {
				msg.append("请输入正确的域名");
				flag = false;
			}
		}
		if (StringUtils.isNotBlank(ratio)) {
			if (ratio.matches("^[+]{0,1}(\\d+)$")) {
				entity.setRatio(ratio);
			} else {
				msg.append("游戏分成为0~100的整数");
				flag = false;
			}
		}
		//运营状态
		if (StringUtils.isNotBlank(gstatus)) {
			entity.setStatus(Integer.parseInt(gstatus));
		} else {
			msg.append("请选择游戏运营状态");
			flag = false;
		}
		//app应用名称
//        if (StringUtils.isNotBlank(app_name)) {
		entity.setApp_name(app_name);
//        }
		//应用图标
		if (StringUtils.isNotBlank(app_icon)) {
			entity.setApp_icon(app_icon);
		}
		//游戏logo
		if (StringUtils.isNotBlank(gameLogo)) {
			entity.setGameLogo(gameLogo);
		}
		entity.setLogingMap(logingMap); //游戏LOGING图
		entity.setLoginMap(loginMap); //游戏登录图
		entity.setIshot(0);
		entity.setIsrecommend(0);
		//展示到网站
		if ("on".equals(display)) {
			entity.setDisplay(0);
//			//游戏地址
//			if (StringUtils.isNotBlank(officialurl)) {
//				entity.setOfficialurl(officialurl);
//			} else {
//				msg.append("游戏官网地址不能为空");
//				flag = false;
//			}
//			//游戏类型
//			if (StringUtils.isNotBlank(gtypes)) {
//				List<Map<String, String>> gtypesList = new ArrayList<Map<String, String>>();
//				String[] list = gtypes.split(",");
//				for (String str : list) {
//					Map<String, String> map = new HashMap<String, String>();
//					String[] strs = str.split("-");
//					map.put("id", strs[0].trim());
//					map.put("name", strs[1].trim());
//					gtypesList.add(map);
//				}
//				entity.setGtypes(JSON.toJSONString(gtypesList));
//			} else {
//				msg.append("请选择游戏类型");
//				flag = false;
//			}
//			//游戏题材
//			if (StringUtils.isNotBlank(gthemes)) {
//				List<Map<String, String>> gthemesList = new ArrayList<Map<String, String>>();
//				String[] list = gthemes.split(",");
//				for (String str : list) {
//					Map<String, String> map = new HashMap<String, String>();
//					String[] strs = str.split("-");
//					map.put("id", strs[0].trim());
//					map.put("name", strs[1].trim());
//					gthemesList.add(map);
//				}
//				entity.setGthemes(JSON.toJSONString(gthemesList));
//			} else {
//				msg.append("请选择游戏题材");
//				flag = false;
//			}
//			//热门，推荐
//			if (StringUtils.isNotBlank(cstatus)) {
//				String[] list = cstatus.split(",");
//				for (String status : list) {
//					if (StringUtils.isNotBlank(status)) {
//						if ("hot".equals(status)) {
//							entity.setIshot(1);
//						}
//						if ("recommend".equals(status)) {
//							entity.setIsrecommend(1);
//						}
//					}
//				}
//			}
//			//pc网站
//			if ("0".equals(terminaltype)) {
//				if (StringUtils.isNotBlank(gstatus)) {
//					if ((StringUtils.isBlank(icon) || StringUtils.isBlank(picture)
//							|| StringUtils.isBlank(rcmdimg) || StringUtils.isBlank(qrcodeimg) || StringUtils.isBlank(bannerimg) || StringUtils.isBlank(detailsimgs)) && "30".equals(gstatus)) {
//						msg.append("游戏状态为正常运营，请上传页面中各项图片");
//						flag = false;
//					}
//					if (StringUtils.isNotBlank(detailsimgs)) {
//						String[] list = detailsimgs.split(",");
//						if (list.length < 3 || list.length > 12) {
//							msg.append("请上传3-12张游戏详情截图");
//							flag = false;
//						}
//					}
//				} else {
//					msg.append("请选择游戏运营状态");
//					flag = false;
//				}
//			}
//			//h5
//			if ("1".equals(terminaltype)) {
//				if (StringUtils.isNotBlank(gstatus)) {
//					if ((StringUtils.isBlank(icon) || StringUtils.isBlank(qrcodeimg)) && "30".equals(gstatus)) {
//						msg.append("游戏状态为正常运营，请上传页面中各项图片");
//						flag = false;
//					}
//				} else {
//					msg.append("请选择游戏运营状态");
//					flag = false;
//				}
//			}
//			//Android手游
//			if ("2".equals(terminaltype) || "3".equals(terminaltype)) {
//				if (StringUtils.isNotBlank(downloadurl)) {
//					//entity.setDownloadurl(downloadurl);
//				} else {
//					msg.append("游戏下载地址不能为空");
//					flag = false;
//				}
//				if (StringUtils.isNotBlank(size)) {
//					if (size.matches("^[1-9]\\d*$")) {
//						//entity.setSize(Double.parseDouble(size));
//					} else {
//						msg.append("请输入正整数游戏包大小");
//						flag = false;
//					}
//				} else {
//					msg.append("游戏包大小不能为空");
//					flag = false;
//				}
//				if (StringUtils.isNotBlank(gstatus)) {
//					if ((StringUtils.isBlank(icon) || StringUtils.isBlank(picture)
//							|| StringUtils.isBlank(rcmdimg) || StringUtils.isBlank(qrcodeimg) || StringUtils.isBlank(bannerimg) || StringUtils.isBlank(detailsimgs)) && "30".equals(gstatus)) {
//						msg.append("游戏状态为正常运营，请上传页面中各项图片");
//						flag = false;
//					}
//					if (StringUtils.isNotBlank(detailsimgs)) {
//						String[] list = detailsimgs.split(",");
//						if (list.length < 3 || list.length > 12) {
//							msg.append("请上传3-12张游戏详情截图");
//							flag = false;
//						}
//					}
//				} else {
//					msg.append("请选择游戏运营状态");
//					flag = false;
//				}
//
//			}
//			if (StringUtils.isNoneBlank(remark)) {
//				entity.setRemark(remark);
//			}
//
//			if (flag) {
//				entity.setDownloadurl(downloadurl);
//				entity.setSize(Double.parseDouble(size));
//				entity.setQrcodeimg(qrcodeimg);
//				entity.setIcon(icon);
//				entity.setPicture(picture);
//				entity.setRcmdimg(rcmdimg);
//				entity.setBannerimg(bannerimg);
//				entity.setSeo_keywords(seo_keywords);
//				entity.setSeo_description(seo_description);
//			}

		} else {
			//不展示到网站
			entity.setDisplay(1);
		}

		entity.setPlayurl(playurl);
		entity.setIsrecharge(isrecharge);
		entity.setDescription(description);

		result.setMessage(msg.toString());
		result.setStatus(flag);
		return result;
	}

	/**
	 * 自身权限下所有子游戏列表
	 *
	 * @return
	 */
	@RequestMapping(value = "/ownerRoleGames")
	public R list() {
		try {
			List<WanGameRes> ownerRoleGames = adRoleGameService.getOwnerRoleGames();
			return R.ok(ownerRoleGames);
		} catch (Exception e) {
			logger.error("获取自身权限下所有子游戏列表失败，失败原因：{}",e);
			return R.failed("获取子游戏列表失败");
		}
	}
}
